﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.IO;

using ProtoBuf;

namespace BartonExtension
{
    public static class SerializeManager
    {
        public static byte[] Serialize(this object o)
        {
            if (o == null)
            {
                return null;
            }
            byte[] buffer = null;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                Serializer.Serialize(memoryStream, o);
                buffer = memoryStream.ToArray();
            }
            return buffer;
        }

        public static void SerializeToFile(this object o, string filename)
        {
            using (var file = System.IO.File.Create(filename))
            {
                ProtoBuf.Serializer.Serialize(file, o);
                file.Close();
            }
        }
        public static T DeserializeFromFile<T>(string filename)
        {
            T obj = default(T);
            if (!File.Exists(filename))
                return obj;

            using (var file = System.IO.File.OpenRead(filename))
            {
                obj = ProtoBuf.Serializer.Deserialize<T>(file);
                file.Close();
            }
            return obj;
        }

        public static T Deserialize<T>(byte[] stream)
        {
            if (stream == null)
            {
                return default(T);
            }

            using (MemoryStream memoryStream = new MemoryStream(stream))
            {
                T result = (T)Serializer.Deserialize<T>(memoryStream);
                return result;
            }
        }
    }
}
